package com.xxgc.moriredis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxgc.moriredis.entity.GoodsEntity;
import com.xxgc.moriredis.entity.GoodsEntityMapper;
import com.xxgc.moriredis.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class GoodServiceImpl implements IGoodsService {

    @Autowired
    private GoodsEntityMapper goodsEntityMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<GoodsEntity> selectGoodsById(String id) {
        // 通过id组成一个key
        String key = "goods:"+id;
        if(redisTemplate.hasKey(key)){ //如果缓存中有这个key
            log.info("缓存中获取的");
            //有了就去缓存中拿
            List<GoodsEntity> goodsEntities = (List<GoodsEntity>) redisTemplate.opsForValue().get(key);
            return goodsEntities;
        }else{ //去数据库查
            log.info("-------------------------------数据中获取的");
            //条件构造器 mybatis plus 官方文档
            QueryWrapper<GoodsEntity> qw = new QueryWrapper<>();
            qw.eq("merchant_id",id);
            List<GoodsEntity> goodsEntities = goodsEntityMapper.selectList(qw);
            //把查询的数据给缓存一份
            redisTemplate.opsForValue().set(
                    key,
                    goodsEntities,
                    30,
                    TimeUnit.SECONDS);
            return goodsEntities;
        }
    }



/*    @Cacheable(value = "goods",key = "#id")
    @Override
    public List<GoodsEntity> selectGoodsById(String id) {
        QueryWrapper<GoodsEntity> qw = new QueryWrapper<>();
        qw.eq("merchant_id",id);
        List<GoodsEntity> goodsEntities = goodsEntityMapper.selectList(qw);
        return goodsEntities;
    }*/
}
